package com.labbit.platform.commons.configs;

import com.labbit.platform.commons.interceptor.AuthorizationInterceptor;
import com.labbit.platform.commons.utils.joda.JodaUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Date;

/**
 * @author ChenYu
 */
@ComponentScan(basePackages = "com.labbit.*")
@Configuration
public class WebAppConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(new AuthorizationInterceptor())
                .addPathPatterns("/**")
                //.excludePathPatterns("/**/login/**")
                .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
    }


    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 时间转换java.util.Date
     *
     * @author ChenYu
     */
    @Bean
    public Converter<String, Date> utilDateConvert() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                if (StringUtils.isEmpty(source)) {
                    return null;
                }
                return JodaUtil.parseTimestamp(source);
            }
        };
    }

    /**
     * 时间转换java.sql.Date
     * @author ChenYu
     */
    @Bean
    public Converter<String, java.sql.Date> sqlDateConvert() {
        return new Converter<String, java.sql.Date>() {
            @Override
            public java.sql.Date convert(String source) {
                if (StringUtils.isEmpty(source)) {
                    return null;
                }
                return new java.sql.Date(JodaUtil.parseDate(source).getTime());
            }
        };
    }
}
